import { Message } from 'element-ui'
import { basicToken } from '@/utils/constant'
import { setToken, removeToken } from '@/utils/auth'
import { getGlobalData } from '@/utils/global_data'

export default function (http) {
  const state = {
    userInfo: null,
    isLogin: false
  }

  const mutations = {
    SET_USERINFO (state, userInfo) {
      state.userInfo = userInfo
    },
    SET_ISLOGIN (state, isLogin) {
      state.isLogin = isLogin
    }
  }

  const actions = {
    // 登录
    login ({ commit }, params) {
      return http.post('/v1/web/auth/authentication/form', params, { headers: { Authorization: basicToken } }).then(resp => {
        let data = resp.data.data
        // 登录拿到 token，并把 token 存到 cookies 中
        let curTime = new Date().getTime()
        let expireTime = curTime + resp.expires_in * 1000
        data.expireTime = expireTime
        let token = data
        setToken(token)
        return 'success'
      }).catch(err => {
        Message.error(err.msg)
        removeToken()
        return 'failed'
      })
    },
    // 退出登录
    logout ({ commit, state }) {
      let router = getGlobalData('router')
      commit('SET_USERINFO', null)
      commit('SET_ISLOGIN', false)
      removeToken()
      router.push({ name: 'login' })
    },
    // 获取用户信息
    getUserInfo ({ commit }) {
      let router = getGlobalData('router')
      return http.get('/v1/web/auth/srb/teachers/info').then(resp => {
        commit('SET_USERINFO', resp)
        commit('SET_ISLOGIN', true)
        router.push({ name: 'home' })
      }).catch((err) => {
        console.log(err)
      })
    }
  }

  return {
    state,
    actions,
    mutations
  }
}
